<template>
  <el-dialog
      :custom-class="showAddressOrPay === 'address' ? '' : 'addCard'"
      @closed="closed"
      @open="open"
      append-to-body
      :title="showAddressOrPay === 'address' ? 'Billing Address' : '' "
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      width="30%">
    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick" v-show="showAddressOrPay === 'pay'">
        <el-tab-pane label="Credit Card" name="card">
          <add-card-form ref="card" :formData.sync="formData" :EditChangeCardNumberAndCvv.sync="EditChangeCardNumberAndCvv"></add-card-form>
        </el-tab-pane>
        <el-tab-pane label="ACH" name="bank">
          <add-bank-form ref="bank" :bankForm.sync="bankForm"></add-bank-form>
        </el-tab-pane>
      </el-tabs>
      <add-address-form ref="address" @setAddress="setAddress" :address="address" v-show="showAddressOrPay === 'address'"/>
    </div>
    <div slot="footer">
        <template v-if="isNext && showAddressOrPay === 'address' && isStep">
          <el-button @click="$emit('update:visible', false)" size="small">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="next" size="small" v-loading="loading">Next</el-button>
        </template>
        <template v-else>
          <el-button style="float: left" size="small" v-if="isNext && isStep" @click="previous">Previous</el-button>
          <el-button @click="$emit('update:visible', false)" size="small">{{$t('cancel')}}</el-button>
          <el-button v-show="false" type="danger" @click="deleteCard(payMethodItem.id)" size="small">delete</el-button>
          <el-button type="primary" @click="submitForm" size="small" v-loading="loading">{{$t('save')}}</el-button>
        </template>
      </div>
  </el-dialog>
</template>

<script>
import addCardForm from '@/views/modules/mspbots/billing/addCardAndAddress/addCardForm'
import addBankForm from '@/views/modules/mspbots/billing/addCardAndAddress/addBankForm'
import addAddressForm from "./addAddressForm.vue";
export default {
  name: 'addCardAndAddress',
  components: {
    addCardForm,
    addBankForm,
    addAddressForm
  },
  // props: ['visible', 'billingData', 'type', 'payMethodItem', 'dialogType'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'pay'
    },
    payType: {
      type: String,
      default: 'card'
    },
    isStep: {
      type: Boolean,
      default: false
    },
    onlyAddress: {
      type: Boolean,
      default: false
    },
    billingData: {
      type: Object,
      default: () => {
        return {
          card: null,
          customer: {}
        }
      }
    },
    payMethodItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data () {
    return {
      loading: false,
      activeName: this.payType || 'card',
      EditChangeCardNumberAndCvv: false,
      formData: {
        firstName: '',
        lastName: '',
        cardNumber: '',
        cardExpiryYear: '',
        cardExpiryMonth: '',
        cardCvv: ''
      },
      bankForm: {
        firstName: '',
        accountNumber: '',
        routingNumber: ''
      },
      addressForm: {
        firstName: '',
        lastName: '',
        address1: '',
        address2: '',
        city: '',
        state: '',
        zip: '',
        country: ''
      },
      cardInfo: null,
      customer: {},
      showAddressOrPay: ''
    }
  },
  computed: {
    dialogVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    isNext () {
      return this.billingData.customer && !this.billingData.customer.primary_payment_source_id && !this.billingData.customer.billing_address.country && this.dialogType === 'address' && !this.onlyAddress;
    },
    address () {
      return this.billingData.customer && this.billingData.customer.billing_address ? this.billingData.customer.billing_address : {}
    }
  },
  watch: {
    payType (val) {
      this.activeName = val
    },
    billingData: {
      handler: function (val) {
        this.customer = val.customer
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    open () {
      this.showAddressOrPay = this.dialogType
      this.$nextTick(() => {
        if (JSON.stringify(this.payMethodItem) !== '{}') {
          if (this.payMethodItem && this.payMethodItem.card) {
            this.cardInfo = this.payMethodItem.card || null
            this.editCard()
            this.activeName = 'card'
            this.EditChangeCardNumberAndCvv = true
          } else {
            this.EditChangeCardNumberAndCvv = false
            this.$nextTick(() => {
              this.reset()
            })
          }
          if (this.payMethodItem && !this.payMethodItem.card) {
            this.activeName = 'bank'
          }
        }
      })
    },
    handleClick () {},
    editCard () {
      // eslint-disable-next-line camelcase
      const { first_name, last_name, masked_number, expiry_month, expiry_year, payment_source_id } = this.cardInfo
      this.formData = {
        paymentSourceId: this.payMethodItem.id,
        firstName: first_name,
        lastName: last_name,
        cardNumber: masked_number,
        cardCvv: '***',
        cardExpiryYear: String(expiry_year),
        cardExpiryMonth: String(expiry_month)
      }
    },
    closed () {
      this.reset()
      // this.$emit('update:visible', false)
    },
    reset () {

      this.$refs['address'].resetForm()
      this.$refs['card'].resetForm()
      this.$refs['bank'].resetForm()
    },
    next () {
      this.$refs['address'].submit().then(() => {
        this.addressForm = this.$refs['address'].form
        if (this.isNext) {
          this.showAddressOrPay = 'pay'
        }
      }).catch(() => {
        console.log('error')
      })
    },
    previous () {
      this.showAddressOrPay = 'address'
    },
    submitForm () {
      // Only for address
      if (!this.isNext && this.dialogType === 'address') {
        this.$refs['address'].submit().then(() => {
          this.saveAddress(this.$refs['address'].form, 'emit')
        }).catch(() => {
          console.log('error')
        })
      } else { // Address and card or bank
        this.$refs[this.activeName].submit().then(async () => {
          if (this.isNext) {
            try {
              await this.saveAddress(this.addressForm)
              if (this.activeName === 'card') {
                await this.submitAddCard(this.formData)
              } else {
                await this.submitAddBank(this.bankForm)
              }
              this.$emit('success')
            } catch (e) {
              console.log(e)
            }

          } else {
            if (this.activeName === 'card') {
              await this.submitAddCard(this.formData, 'emit')
            } else {
              await this.submitAddBank(this.bankForm, 'emit')
            }
          }
        })
      }
    },
    async submitAddCard (formData, emit) {
      this.loading = true
      if (this.cardInfo && this.payMethodItem.id && formData.cardCvv === '***' && formData.cardNumber === this.cardInfo.masked_number) {
        this.loading = false
        return this.editCardRequest(formData)
      }
      const params = {
        customerId: this.customer.id,
        ...formData
      }
      const { createPaymentSource } = this.$interface.pay
      try {
        const { data } = await createPaymentSource(params)
        if (data.code !== 0) {
          this.$message.error(data.msg)
        } else {
          if (this.cardInfo && this.payMethodItem.id) {
            await this.deleteCard(this.payMethodItem.id)
          }
          this.dialogVisible = false
          if (emit) {
            this.$emit('success')
          }
        }
        this.loading = false
      } catch (e) {
        console.log(e)
      }
    },
    async submitAddBank (formData, emit) {
      this.loading = true
      const params = {
        customerId: this.customer.id,
        ...formData
      }
      const { createBankAccount } = this.$interface.pay
      try {
        const { data } = await createBankAccount(params)
        if (data.code !== 0) {
          this.$message.error(data.msg)
        } else {
          if (this.payMethodItem && this.payMethodItem.id) {
            await this.deleteCard(this.payMethodItem.id)
          }
          this.dialogVisible = false
          if (emit) {
            this.$emit('success')
          }
        }
        this.loading = false
      } catch (e) {
        console.log(e)
      }
    },
    async editCardRequest (formData) {
      delete formData.cardNumber
      delete formData.cardCvv
      const params = {
        ...formData
      }
      const { editPaymentSource } = this.$interface.pay
      try {
        const { data } = await editPaymentSource(params)
        if (data.code !== 0) {
          this.$message.error(data.msg)
        } else {
          this.dialogVisible = false
          this.$emit('success')
        }
      } catch (e) {
        console.log(e)
      }
    },
    async deleteCard (id) {
      const { deletePaymentSource } = this.$interface.pay
      try {
        const { data } = await deletePaymentSource(id)
        if (data.code !== 0) {
          this.$message.error(data.msg)
        } else {
          // this.$emit('update:visible', false)
          // this.$emit('success')
        }
      } catch (e) {
        console.log(e)
      }
    },
    setAddress (val) {
      this.addressForm = val
    },
    async saveAddress (val, emit) {
      this.loading = true
      const params = Object.assign({ customerId: this.customer.id }, val)
      const { savePaywallAddress } = this.$interface.pay
      const { data } = await savePaywallAddress(params)
      this.loading = false
      if (data.code === 0) {
        this.dialogVisible = false
        if (emit) {
          this.$emit('success')
        }
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .addCard {
  .el-dialog__header {
    padding: 0;
  }
}
::v-deep .el-tabs__content {
  overflow: hidden;
}
::v-deep .el-dialog__body {
  padding-top: 0;
}
::v-deep .el-tabs__nav {
  display: block;
  width: 100%;
  .el-tabs__item {
    width: 50%;
    text-align: center;
    height: 50px;
    line-height: 50px;
  }
}
::v-deep .el-form-item {
  margin-bottom: 15px;
}
</style>
